import time
import pymysql

from tools.log import GetLogging

logger = GetLogging().get_logging()

class DatabaseProcess:

    def __init__(self):
        self.conn = pymysql.connect(
            host="192.168.153.131",
            port=3306,
            user="tastshop",
            password="123456",
            database="tastshop"
        )
        self.cursor = self.conn.cursor()

    def __del__(self):
        if hasattr(self, "conn"):
            self.conn.close()
        if hasattr(self, "cursor"):
            self.cursor.close()

    # 获取数据库中最大的Id
    def get_max_id(self, table):
        try:
            self.cursor.execute(f"select MAX(id) from {table}")
            result = self.cursor.fetchone()
            logger.info(f"成功获取到最大ID，表名为：{table}，id为：{result[0]}")
            return result[0] if result[0] is not None else 0
        except Exception as e:
            logger.error(f"获取{table}最大ID失败: {str(e)}")
            return None

    # 获取数据库中订单的Id
    def get_database_order(self):
        return self.get_max_id("sxo_order")

    # 获得数据库中订单售后的Id
    def get_database_order_aftersale(self):
        return self.get_max_id("sxo_order_aftersale")

    # 获得数据库中购物车的Id
    def get_database_cart_id(self):
        return self.get_max_id("sxo_cart")

    # 获得数据库中商品浏览历史的Id
    def get_database_goods_browse(self):
        return self.get_max_id("sxo_goods_browse")

    # 获得数据库中地址的Id
    def get_database_user_address(self):
        return self.get_max_id("sxo_user_address")

    # 添加商品浏览历史/足迹
    def add_goods_browse(self, goods_id=104, user_id=47):
        try:
            current_time = int(time.time())
            insert_sql = """
                    INSERT INTO sxo_goods_browse (goods_id, user_id, add_time, upd_time) 
                    VALUES (%s, %s, %s, %s)
                    """
            self.cursor.execute(insert_sql, (goods_id, user_id, current_time, current_time))
            self.conn.commit()
            logger.info(f"成功添加商品浏览历史，商品ID：{goods_id}，用户ID：{user_id}")
        except Exception as e:
            self.conn.rollback()
            logger.error(f"添加浏览历史记录失败，商品ID：{goods_id}，用户ID：{user_id}，错误信息：{str(e)}")

    # 确认支付商品
    def update_orders(self, status=2, pay_status=1, pay_price=56390.00, order_id=0):
        try:
            update_sql = """
                    UPDATE `sxo_order` SET `status` = %s, `pay_status` = %s, `pay_price` = %s WHERE `id` = %s
                    """
            self.cursor.execute(update_sql, (status, pay_status, pay_price, order_id))
            self.conn.commit()
            logger.info(f"成功更新订单支付状态，订单ID：{order_id}，状态：{status}，支付状态：{pay_status}，支付金额：{pay_price}")
        except Exception as e:
            self.conn.rollback()
            logger.error(f"更新订单支付状态失败，订单ID：{order_id}，错误信息：{str(e)}")

    # 商品发货
    def update_order_express(self, status=3, order_id=0, user_id=47, express_id=1, express_number=498919):
        try:
            current_time = int(time.time())
            insert_sql = """
            INSERT INTO sxo_order_express (order_id, user_id, express_id, express_number,add_time) 
                    VALUES (%s, %s, %s, %s, %s)
            """
            update_sql = """
                    UPDATE `sxo_order` SET `status` = %s WHERE `id` = %s
                    """
            self.cursor.execute(update_sql, (status, order_id))
            self.cursor.execute(insert_sql, (order_id, user_id, express_id, express_number, current_time))
            self.conn.commit()
            logger.info(f"成功完成商品发货，订单ID：{order_id}，状态：{status}，快递ID：{express_id}，快递单号：{express_number}")
        except Exception as e:
            self.conn.rollback()
            logger.error(f"商品发货失败，订单ID：{order_id}，错误信息：{str(e)}")

    # 确认退货申请
    def update_order_aftersale(self, status=1, order_after_id=0):
        try:
            update_sql = """
                    UPDATE `sxo_order_aftersale` SET `status` = %s WHERE `id` = %s
                    """
            self.cursor.execute(update_sql, (status, order_after_id))
            self.conn.commit()
            logger.info(f"成功确认退货申请，订单售后ID：{order_after_id}，状态：{status}")
        except Exception as e:
            self.conn.rollback()
            logger.error(f"确认退货申请失败，订单售后ID：{order_after_id}，错误信息：{str(e)}")

    # 删除注册的用户
    def delete_register_user(self, min_user_id=48):
        try:
            delete_sql = """
            DELETE FROM sxo_user WHERE `id` >= %s
            """
            self.cursor.execute(delete_sql,min_user_id)
            self.conn.commit()
            logger.info(f"成功删除用户，删除条件：ID >= {min_user_id}")
        except Exception as e:
            self.conn.rollback()
            logger.error(f"删除用户失败，删除条件：ID >= {min_user_id}，错误信息：{str(e)}")
